#!/usr/bin/env node
const fs = require('fs');
const dayjs = require('dayjs');
const  { execSync } = require('child_process')
const bzipConfig = require('./.bzip.config.js')

const PACKAGE_JSON_PATH = bzipConfig.packageUrl;
const VERSIONLINE_PATH = bzipConfig.versionLineUrl;
const MANIFEST_JSON_PATH = bzipConfig.manifestUrl;

async function readPackageJson() {
  const json = await fs.promises.readFile(PACKAGE_JSON_PATH, "utf8");
  return JSON.parse(json);
}

async function enterDescription() {
  const inquirer = await import('inquirer');
  const { describe } = await inquirer.default.prompt([
    {
      type: "input",
      name: "describe",
      message: "请输入打包描述信息（回车键确认）：",
      validate(value) {
        return !value ? new Error("打包描述不能为空") : true;
      },
    },
  ]);
  return describe;
}

async function generateVersionInfo(currentVersion) {
  const currentDate = dayjs().format("YYYYMMDD");
  let versionNumber =
    currentVersion === "1.0.0"
      ? `1.${currentDate}.1`
      : `1.${currentDate}.${
          currentDate === currentVersion.split(".")[1]
            ? parseInt(currentVersion.split(".")[2], 10) + 1
            : 1
        }`;

  const tips = await enterDescription();
  const time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  const name = (execSync("git config user.name") || Buffer.from("未知用户"))
    .toString()
    .trim();

  return {
    versionNumber,
    data: { time, tips, name },
  };
}

async function updatePackageJson(packageJson, versionInfo) {
  packageJson.version = versionInfo.versionNumber;
  try {
    await fs.promises.writeFile(
      PACKAGE_JSON_PATH,
      JSON.stringify(packageJson, null, 2)
    );
    console.log("版本号更改成功");
  } catch (error) {
    console.error("版本号更改失败:", error);
  }
}

function getVersionLine() {
  let versionLine = {};
  try {
    versionLine = JSON.parse(fs.readFileSync(VERSIONLINE_PATH, 'utf8'));
  } catch (e) {
    // 生成文件
    fs.writeFileSync(VERSIONLINE_PATH, '{}');
  }
  return versionLine;
}

async function writeVersionLine(versionInfo) {
  const versionLine = getVersionLine();
  versionLine[versionInfo.versionNumber] = versionInfo.data;
  try {
    await fs.promises.writeFile(
      VERSIONLINE_PATH,
      JSON.stringify(versionLine, null, 2)
    );
    console.log("版本信息写入成功");
  } catch (error) {
    console.error("版本信息写入失败:", error);
  }
}

function getManifestJson(){
  let manifestJson = {};
  try {
    manifestJson = JSON.parse(fs.readFileSync(MANIFEST_JSON_PATH, 'utf8'));
  } catch (e) {
    // 生成文件
    fs.writeFileSync(MANIFEST_JSON_PATH, '{}');
  }

  return manifestJson;
}

async function writeManifestJson(versionInfo){
  const manifestJsonContent = getManifestJson()
  manifestJsonContent['versionName'] = versionInfo.versionNumber
  manifestJsonContent['timestamp'] = Date.now()
  manifestJsonContent['versionMsg'] = versionInfo.data.tips
  try {
    await fs.promises.writeFile(MANIFEST_JSON_PATH, JSON.stringify(manifestJsonContent, null, 2));
    console.log('manifest.json写入成功');
  } catch (error) {
    console.error('manifest.json写入失败:', error);
  }
}

async function main() {
  try {
    const packageJson = await readPackageJson();
    const versionInfo = await generateVersionInfo(packageJson.version);
    await updatePackageJson(packageJson, versionInfo);
    await writeVersionLine(versionInfo);
    await writeManifestJson(versionInfo);
  } catch (error) {
    console.error("脚本执行失败:", error);
  }
}

main();
